  package com.emode.action;

import java.io.*;
import java.util.*;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.emode.base.BaseAction;
import com.emode.entity.Bbsreply;
import com.emode.entity.Bbsusers;
import com.emode.entity.SysGroup;
import com.emode.entity.UserFollow;
import com.emode.qiniu.api.QiniuApi;
import com.emode.util.CommonUtils;
import com.emode.util.CookiesUtil;
import com.emode.util.FileUtil;
import com.opensymphony.xwork2.ActionContext;
public class UserAction extends BaseAction<Bbsusers> implements SessionAware{
	/*
	 * 
	 */
	private static final long serialVersionUID = -3556586124161294936L;
	private File[] file;
	private String[] fileFileName;
	private String[] fileContentType;
	
	
	 //Struts2中Map类型的session
	Map<String, Object> session;
    //接收客户端传来的验证码
    private String securityCode;
	
	//跳转 login
	public String tologin(){
		return "tologin";
		
	}
	//跳转 toreg
	public String toreg(){
		return "toreg";
		
	}
	//用户登录
	/*
	 * 用户登录可以尝试单点登录
	 */
	 
	public void login()throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		HttpSession session = ServletActionContext.getRequest().getSession();
		if(null==model.getUname()||null==model.getUpassword()){
			map.put("status", false);
			map.put("content", "用户名或密码不能为空！");
			CommonUtils.resultMapToJson(map);
		}
		Bbsusers user = userservice.find(model);
		if(user == null){
			map.put("status", false);
			map.put("content","用户名或密码错误，请重新输入");
			//CommonUtils.returnJson(msg);
			CommonUtils.resultMapToJson(map);
		}
		else {
			
			if(4==user.getUstate()){
				map.put("status", false);
				map.put("content", "该账户被封禁");
				CommonUtils.resultMapToJson(map);
			}
			//得到系统当前的时间
			user.setLastlogin(new Date());
			userservice.updateLoginDate(user);
			//ActionContext.getContext().getSession().put("user", user);
			session.setAttribute("user", user);
			CookiesUtil.addCookie("login_bbs", user.getUname());
			CookiesUtil.addCookie("login_key", user.getUpassword());
			map.put("status", true);
			map.put("content", "登录成功");
			CommonUtils.resultMapToJson(map);
		}
	}
	//ajax 校验
	public String checkLogin()throws Exception{
		Bbsusers user = userservice.find(model);
		if(user==null){
			msg="false";
			CommonUtils.returnJson(msg);
		}else{
			msg="true";
			CommonUtils.returnJson(msg);
		}
		return null;
	}
	//退出
	public String logout(){
		ActionContext.getContext().getSession().remove("user");
		return "logout";
	}
	/*
	 * 密码md5 
	 * 邮箱激活
	 */
		//用户注册
	/*
	 * 注册时用线程锁，防止同一个用户名或邮箱注册多个账户
	 */
	public String reg() throws Exception{
		Map<String,String> errors = validateRegist();
		if(errors.size()>0){
			 Map<Object, Object> info = new HashMap<Object, Object>();
			 info.put("errors", errors);
			 System.out.println(info.toString());
			 ActionContext.getContext().put("errors", info);
			return "toreg";	
		}else{
			String passwordMD5 = DigestUtils.md5Hex(model.getUpassword());
			model.setUpassword(passwordMD5);
			
			model.setActivationCode(CommonUtils.uuid()+CommonUtils.uuid());
			model.setUregDate(new Date());
			//model.setGroup(group);
			//userservice.save(model);
			SysGroup group = groupservice.getById(2);
			userservice.userReg(model,group);
//			SysGroup group = new SysGroup();
//			group.setGroupid(2);//设置默认用户组
//			model.getGroup().add(group);
//			userservice.update(model);
			msg = "注册成功，请登录!";
			return "tologin";	
		}
	}
	//对用户提交的表单校验
		/*
		 * 对用户名校验是否重复
		 * 邮箱
		 * 密码
		 * 验证码
		 * 
		 */
	public Map<String,String> validateRegist() throws Exception{
		Map<String,String> errors = new HashMap<String,String>();
		/*
		 * 校验用户名
		 */
		String loginname = model.getUname();
		if(loginname==null||loginname.trim().isEmpty()){
			errors.put("loginname", "用户名不能为空");
		}else if(loginname.length()<3||loginname.length()>20){
			errors.put("loginname", "用户名长度需要3到20之间");
		}else if(!getResult()){
			errors.put("loginname", "该用户已注册，不可用");
		}
		/*
		 * 用户密码校验
		 */
		
		String loginpass = model.getUpassword();
		if(loginpass==null||loginpass.trim().isEmpty()){
			errors.put("loginpass", "密码不能为空");
		}else if(loginpass.length()<5||loginpass.length()>20){
			errors.put("loginpass", "用户密码长度需在3到20之间");
		}
		/*
		 * 用户邮箱校验
		 */
		String loginemail = model.getUemail();
		if(loginemail==null||loginemail.trim().isEmpty()){
			errors.put("loginemail", "邮箱不能为空");
		}else if(!loginemail.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$")){
			errors.put("loginemail", "邮箱格式不对");
		}else if(!getResult()){
			errors.put("loginemail", "该邮箱已注册，不可用");
		}
		/*
		 * 验证码校验
		 */
		 String serverCode = (String)session.get("SESSION_SECURITY_CODE");
		 if(serverCode==null||serverCode.trim().isEmpty()){
			 errors.put("serverCode", "验证码不能为空");
		 }else if(!serverCode.equals(securityCode)){
			 errors.put("serverCode", "您输入的验证码不正确，请重新输入");
		 }
			
		return errors;
		
	}
		
	//用户校验
	public String ValidateName() throws Exception {
		String msg = "true";
		boolean flag =  getResult();
		System.out.println(flag);
		if(!flag){
			msg = "false";
		}
		CommonUtils.returnJson(msg);
		return null;
		
	}
	//邮箱校验
	public String ValidateEmail() throws Exception {
		String msg = "true";
		boolean flag =  getResult();
		if(!flag){
			msg = "false";
		}
		CommonUtils.returnJson(msg);
		return null;
		
	}
	/*
	 * 对用户名和邮箱查询
	 */
	public boolean getResult() throws IOException {
		boolean flag  =false;
		Bbsusers user = userservice.find(model);
		if(user==null){
			flag = true;
			return flag;
			
		}
		return flag;
	}
		
	//验证码校验
	public String ValidateCode() throws Exception{
		//得到系统产生的验证码
		 String serverCode = (String)session.get("SESSION_SECURITY_CODE");
		 //拿到客户传过来的验证码和系统验证码比较
		 if(!serverCode.equals(securityCode)){
			 msg = "false";
			 CommonUtils.returnJson(msg);
		 }else{
			 msg="true";
			 CommonUtils.returnJson(msg);
		 }
		return null;
	}
	
	//list 显示所有用户
	public String all() throws Exception{
		List<Bbsusers> users = userservice.findAll();
		//ActionContext.getContext().getSession().put("users", users);
		ActionContext.getContext().put("users", users);
		return "allusers";
	}
	
	// 用户详情
	public String userDetails()throws Exception{
		System.out.println("start"+model.getUid());
		Bbsusers user = userservice.getById(model.getUid());
		list = topicservice.findTopicByUid(model.getUid());
		List<Bbsreply> replyList = replyservice.getReplyByTime(model.getUid());
		ActionContext.getContext().put("u", user);
		ActionContext.getContext().put("list2", list);
		ActionContext.getContext().put("reply", replyList);
		return "userDetail";
	}
	//通过uname查找用户
	public String searchUser() throws Exception{
		list = userservice.findUsers(model.getUname());
		if(list.size()>0){
			return "searchresult";
		}else{
			msg = "没有找到搜索结果";
			return msg;
		}
	}

	
	//用户 设置
	public String setProfile() throws Exception{
		//model.setUid(getCurrentUser().getUid());
		Bbsusers user  =  userservice.getById(getCurrentUser().getUid());
		ActionContext.getContext().put("u", user);
		return "profile";
		
	}
	//更新profile
	public void updateProfile(){
		Bbsusers user = getCurrentUser();
		user.setUemail(model.getUemail());
		user.setUremark(model.getUremark());
		user.setHomepage(model.getHomepage());
		userservice.update(user);
		ActionContext.getContext().getSession().put("user", user);
		msg="true";
		CommonUtils.returnJson(msg);
	}
	//关注
	public  void follow(){
		if(model.getUid()!=null){
			System.out.println(model.getUid());
			int toUserId = model.getUid();
			Bbsusers fromUser = getCurrentUser();
		if(fromUser.getUid().equals(toUserId)){
			System.out.println("不能关注自己");
			CommonUtils.returnJson("不能关注自己");
		}else{
			Bbsusers toUser = userservice.getById(toUserId);
			UserFollow userFollow = new UserFollow();
			userFollow.setBbsusersByUid(fromUser);
			userFollow.setBbsusersByFolloweduser(model);
			userFollow.setAddtime(new Date());
			followService.save(userFollow);
			userservice.updateFollow(toUser,fromUser );
			ActionContext.getContext().getSession().put("user",userservice.getById(fromUser.getUid()));
			System.out.println(ActionContext.getContext().getSession());
			CommonUtils.returnJson("关注成功");
		}
		}else{
			CommonUtils.returnJson("关注出错");
		}
	}
	public String setAvatar(){
		return "setavatar";
		
	}
	//跳转到设置密码页面
	public String setPsw(){
		return "setpsw";
	}
	//跳转到忘记密码页面
	public String to_forgetpsw(){
		return "toforgetpsw";
	}
	/*
	 * 修改密码 得到当前的密码，和系统密码对比，
	 * 当一致是修改
	 */
	public void confirmPsw(){
		String pass = DigestUtils.md5Hex(model.getUpassword());
		if(getCurrentUser().getUpassword().equals(pass)){
			Bbsusers user = getCurrentUser();
			user.setUpassword(DigestUtils.md5Hex(model.getRepsw()));
			userservice.update(user);
			msg="true";
			CommonUtils.returnJson(msg);
		}else{
			msg="false";
			 CommonUtils.returnJson(msg);
		}
	}
	/*
	 * 上传头像  上传的路径为工程的webapp下面，tomcat重启会删除upload
	 */
	public String upAvatar() throws IOException{
		Bbsusers user =getCurrentUser();
		String photopath = "upload\\avatar\\";
		for(int i=0;i<file.length;i++){
			if(file[i].length()>0){
				String filePath = FileUtil.fileCopy(file[i], fileFileName[i],photopath);
				filePath = filePath.replace("\\", "/");
				filePath = FileUtil.getWebRootPath()+filePath;
				String key = String.valueOf(user.getUid());
				fileservice.upload(key, filePath);
				String path =  QiniuApi.getUrlByKey(user.getUid().toString());
				System.out.println(path);
				user.setAvatar(path);	
				userservice.update(user);
			}
		}
		return "profile";
		
	}
	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	public String getSecurityCode() {
		return securityCode;
	}
	public void setSecurityCode(String securityCode) {
		this.securityCode = securityCode;
	}
	
	
	public File[] getFile() {
		return file;
	}
	public void setFile(File[] file) {
		this.file = file;
	}
	
	public String[] getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(String[] fileFileName) {
		this.fileFileName = fileFileName;
	}
	public String[] getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(String[] fileContentType) {
		this.fileContentType = fileContentType;
	}
}
